﻿using System;
using System.Collections.Generic;
using Core.AdminGroupMenuPermission;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Cache;
using DataObject.QA;

namespace CMS.Controls.QA
{
    public partial class CreateOrEdit : AuthenticatedControl
    {
        protected int Id;
        protected string ReturnUrl;
        protected string Action;
        protected string CurrentTab;

        protected void Page_Load(object sender, EventArgs e)
        {
            ReturnUrl = Utils.GetIdFromRequestString(Utils.ReturnUrl, string.Empty);
            Action = Utils.GetIdFromRequestString(Utils.Action, string.Empty);
            Id = Utils.GetIdFromRequestString(Utils.Id, 0);

            if (!IsPostBack)
            {
                ltTitle.Text = Id > 0 ? "Sửa QA" : "Tạo QA";

                ActionPermission();

                if (Id > 0)
                {
                    BindAnswer(Id);
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "quiz", "<script>binDataQA(" + Id + ");</script>");
                }
            }
        }

        #region Action Permission

        public void ActionPermission()
        {
            var isShowPublished = false;

            var adminGroupMenuPermission =
                    AdminGroupMenuPermissionController.AdminGroupMenuPermission_GetBy_AdminUserId_AdminMenuId(CurrentUser.AdminUserId, cControl.AdminMenuId);
            if (adminGroupMenuPermission.Count > 0)
            {
                foreach (var agmp in adminGroupMenuPermission)
                {
                    isShowPublished = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanPublish);
                }
            }

            foreach (var t in Utils.Tabs)
                if (ReturnUrl.IndexOf(t) != -1)
                    CurrentTab = t;

            if (!string.IsNullOrEmpty(CurrentTab))
            {
                // Nếu action là Tạo mới thì nút Save mới được hiển thị
                if (Action.ToLower().Equals("create"))
                    CurrentTab = Utils.IsWaitingForPublish;

                switch (CurrentTab)
                {
                    // Chờ duyệt                        
                    case "IsWaitingForPublish":
                        btnPublish.Visible = isShowPublished;
                        btnDelete.Visible = isShowPublished;
                        btnSave.Visible = isShowPublished;
                        break;
                    // Đã duyệt                    
                    case "IsPublished":
                        btnDelete.Visible = isShowPublished;
                        btnSave.Visible = isShowPublished;
                        break;
                }
            }
            else
            {
                btnPublish.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
            }
        }

        #endregion

        #region Manager Action

        public void ManagerAction(string action)
        {
            QAObject qs;

            var isActive = false;
            var id = Utils.GetIdFromRequestString(Utils.Id, 0);
            var isFeature = cbIsFeature.Checked;

            switch (action)
            {
                case Const.Action.Publish:
                    isActive = true;
                    break;
            }

            if (Id > 0)
            {
                switch (action)
                {
                    case Const.Action.Delete:
                        QAController.QA_Answer_DeleteAll(id); 
                        QAController.QA_Delete(id);
                        Response.Redirect(ReturnUrl);
                        break;
                }

                qs = QAController.QA_GetById(id);
                if (qs != null)
                {
                    qs.QA_ID = id;
                    qs.QA_Text = txtText.Text;
                    qs.QA_IsFeature = isFeature;
                    if(action != Const.Action.Save) qs.QA_IsActive = isActive;
                    qs.QA_Name = txtName.Text;
                    qs.QA_Email = txtEmail.Text;

                    QAController.QA_Update(qs); // update                     
                    CreateAnswer(id); // create answer
                }
            }
            else
            {
                qs = new QAObject();
                qs.QA_Text = txtText.Text;
                qs.QA_IsFeature = isFeature;
                qs.QA_IsHighlight = false;
                qs.QA_IsActive = false;
                qs.QA_Name = txtName.Text;
                qs.QA_Email = txtEmail.Text;
                qs.QA_ReplyTo = 0;

                var identityId = QAController.QA_Create(qs); // create quizzshop return identity id
                if (identityId > 0)
                {
                    CreateAnswer(identityId); // create small size
                }
            }
            CacheController.RemoveCachePort(Constants.ManagerCacheGroup.QA);
            Response.Redirect(ReturnUrl);
        }

        #endregion

        #region Bind Answer

        public void BindAnswer(int id)
        {
            var o = QAController.QA_GetById(id);
            if (o != null)
            {
                txtText.Text = o.QA_Text;
                cbIsFeature.Checked = o.QA_IsFeature;
                ltCreatedDate.Text = DateTimeFunctions.FormatIn_HHMM_DDMMYYYY(o.QA_CreatedDate);
                txtName.Text = o.QA_Text;
                txtEmail.Text = o.QA_Email;
            }
        }

        #endregion

        #region Create Small Size

        public void CreateAnswer(int id)
        {
            // auto get data from javascript
            var contentList = txtContentList.Text;

            if (!string.IsNullOrEmpty(contentList))
            {
                var lstResult = new List<string>();

                // list image
                string[] splitResult = contentList.Split('►');
                if (splitResult.Length > 0)
                    for (var i = 0; i < splitResult.Length; i++)
                        if (!string.IsNullOrEmpty(splitResult[i]))
                            lstResult.Add(splitResult[i]);

                // sample check 
                if (lstResult.Count > 0)
                {
                    QAController.QA_Answer_DeleteAll(id); // delete all small size by quizzyshopId

                    for (int i = 0; i < lstResult.Count; i++)
                    {
                        var o = new QAObject();

                        o.QA_Text = lstResult[i];
                        o.QA_IsFeature = false;
                        o.QA_IsHighlight = false;
                        o.QA_IsActive = true;
                        o.QA_Name = CurrentUser.Username;
                        o.QA_Email = CurrentUser.Email;
                        o.QA_ReplyTo = id;
                        QAController.QA_Create(o);
                    }
                }
            }
        }

        #endregion

        #region Buttons

        protected void BtnSave(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Save);
        }

        protected void BtnPublish(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Publish);
        }

        protected void BtnDelete(object sender, EventArgs e)
        {
            ManagerAction(Const.Action.Delete);
        }

        #endregion               
    }
}